<template>
  <div class="project-report-detail">
    <div>
      <van-skeleton title :row="5" :loading="loading">
        <van-form ref="form" @submit="formSubmited">
          <van-field
            v-model="form.serialNum"
            name="serialNum"
            label="编号"
            placeholder="保存后自动生成编号"
            disabled
            v-show="pageType == 1"
          />

          <van-field
            name="reportPeople"
            label="报备来源"
            required
            :rules="[{required:true,message:'请选择报备来源',trigger:'onChange'}]"
            :disabled="!canEdit"
          >
            <template #input>
              <van-radio-group
                v-model="form.reportPeople"
                direction="horizontal"
                :disabled="!canEdit"
              >
                <van-radio
                  :name="item.value"
                  v-for="item in reportPeopleArr"
                  :key="item.value"
                >{{ item.text }}</van-radio>
              </van-radio-group>
            </template>
          </van-field>

          <van-field
            v-model="showForm.cusAddDocumentId_show"
            name="cusAddDocumentId"
            label="地产名称"
            placeholder="请选择地产名称"
            required
            readonly
            clickable
            :rules="[{ validator:cusAddDocsValidate, message: '请输入正确内容' }]"
            :disabled="!canEdit"
            @click="openFuzzyPopup('cusAddDocumentId','cusFullName')"
          />
          <van-popup v-model="popupVisible" position="top" @opened="fuzzyPopupOpened">
            <div class="salesmanPopupContainer">
              <van-search
                ref="popupDom"
                v-model="searchValue"
                placeholder="请输入搜索关键词"
                :show-action="showSearchAdd"
                @input="fuzzyInput"
                @clear="fuzzyClear"
              >
                <template #action>
                  <div @click="fuzzyAdd" style="color:#1989fa">添加</div>
                </template>
              </van-search>
              <div class="salesmanItemContainer">
                <div
                  v-for="item in searchArray"
                  :key="'' + item.id + Math.random()"
                  @click="fuzzyItemClick(item)"
                  class="salesmanItem van-hairline--bottom"
                >{{ item[popupCtr.showKey] }}</div>
              </div>
            </div>
          </van-popup>

          <van-field
            name="realEstateProp"
            label="地产性质"
            required
            :rules="[{required:true,message:'请选择地产性质',trigger:'onChange'}]"
            :disabled="!canEdit"
          >
            <template #input>
              <van-radio-group
                v-model="form.realEstateProp"
                direction="horizontal"
                :disabled="!canEdit"
              >
                <van-radio
                  :name="item.value"
                  v-for="item in realEstatePropArr"
                  :key="item.value"
                >{{ item.text }}</van-radio>
              </van-radio-group>
            </template>
          </van-field>

          <van-field
            name="realEstateLevel"
            label="地产等级"
            required
            :rules="[{required:true,message:'请选择地产等级',trigger:'onChange'}]"
            :disabled="!canEdit"
          >
            <template #input>
              <van-radio-group
                v-model="form.realEstateLevel"
                direction="horizontal"
                :disabled="!canEdit"
              >
                <van-radio
                  :name="item.value"
                  v-for="item in realEstateLevelArr"
                  :key="item.value"
                >{{ item.text }}</van-radio>
              </van-radio-group>
            </template>
          </van-field>

          <van-field
            v-model="form.projectName"
            name="projectName"
            label="项目名称"
            placeholder="请输入项目名称"
            required
            :disabled="!canEdit"
            :rules="[ { required:true, message:'请输入项目名称' } ]"
          />

          <van-field
            v-model="form.projectSite"
            name="projectSite"
            label="工程地点"
            placeholder="请输入工程地点"
            required
            :disabled="!canEdit"
            :rules="[ { required:true, message:'请输入工程地点' } ]"
          />

          <van-field
            name="proToGround"
            label="项目落地"
            required
            :rules="[{required:true,message:'请选择项目落地',trigger:'onChange'}]"
            :disabled="!canEdit"
          >
            <template #input>
              <van-radio-group
                v-model="form.proToGround"
                direction="horizontal"
                :disabled="!canEdit"
                @change="proToGroundChange"
              >
                <van-radio
                  :name="item.value"
                  v-for="item in proToGroundArr"
                  :key="item.value"
                >{{ item.text }}</van-radio>
              </van-radio-group>
            </template>
          </van-field>

          <van-field
            v-model="showForm.engineerAgentCusId_show"
            name="engineerAgentCusId"
            label="代理商"
            placeholder="请选择代理商"
            readonly
            clickable
            :required="form.proToGround == '2' || form.proToGround == '3' "
            :disabled="engineerAgentCusIdDisabled || !canEdit"
            :rules="[{ validator:engineerAgentCusIdValidate, message: '请输入选择代理商' }]"
            @click="()=>{if(!engineerAgentCusIdDisabled){openFuzzyPopup('engineerAgentCusId','cusFullName',true)}}"
          />

          <van-field
            v-model="form.mainPerson"
            name="mainPerson"
            label="项目对接人"
            placeholder="请输入项目对接人"
            required
            :disabled="!canEdit"
            :rules="[ { required:true, message:'请输入项目对接人' } ]"
          />

          <van-field
            v-model="form.duty"
            name="duty"
            label="职务"
            required
            placeholder="请输入职务"
            :disabled="!canEdit"
            :rules="[ { required:true, message:'请输入职务' } ]"
          />

          <van-field
            v-model="form.mainPerPhone"
            name="mainPerPhone"
            label="电话"
            required
            placeholder="请输入电话"
            :disabled="!canEdit"
            :rules="[ { required:true, message:'请输入电话' } ]"
          />

          <van-field
            v-model="form.mainPerson2"
            name="mainPerson2"
            label="项目对接人2"
            placeholder="请输入项目对接人"
            :disabled="!canEdit"
          />

          <van-field
            v-model="form.duty2"
            name="duty2"
            label="职务2"
            placeholder="请输入职务"
            :disabled="!canEdit"
          />

          <van-field
            v-model="form.mainPerPhone2"
            name="mainPerPhone2"
            label="电话2"
            placeholder="请输入电话"
            :disabled="!canEdit"
          />

          <van-field
            v-model="form.mainPerson3"
            name="mainPerson3"
            label="项目对接人3"
            placeholder="请输入项目对接人"
            :disabled="!canEdit"
          />

          <van-field
            v-model="form.duty3"
            name="duty3"
            label="职务3"
            placeholder="请输入职务"
            :disabled="!canEdit"
          />

          <van-field
            v-model="form.mainPerPhone3"
            name="mainPerPhone3"
            label="电话3"
            placeholder="请输入电话"
            :disabled="!canEdit"
          />

          <van-field
            name="construcProgress"
            label="项目进度"
            required
            :disabled="!canEdit"
            :rules="[{ required:true, message:'请选择项目进度', trigger:'onChange' }]"
          >
            <template #input>
              <van-radio-group
                v-model="form.construcProgress"
                direction="horizontal"
                :disabled="!canEdit"
              >
                <van-radio
                  :name="item.value"
                  v-for="item in construcProgressArr"
                  :key="item.value"
                >{{ item.text }}</van-radio>
              </van-radio-group>
            </template>
          </van-field>

          <van-field
            v-model="showForm.salesmanId_show"
            name="salesmanId"
            label="跟进业务员"
            placeholder="请选择跟进业务员"
            required
            readonly
            clickable
            :disabled="!canEdit"
            :rules="[{ validator:salesmanValidate, message: '请输入正确内容' }]"
            @click="openFuzzyPopup('salesmanId','nickName')"
          />

          <van-field
            v-model="form.phone"
            name="phone"
            label="手机"
            placeholder="请输入手机号"
            type="number"
            required
            :disabled="!canEdit"
            :rules="[ { validator: (val)=>{ return val ? /^1[3456789]\d{9}$/.test(val) : true }, message:'请输入正确的手机号' } ]"
          />

          <van-field
            v-model="form.projectRemark"
            name="projectRemark"
            label="项目描述"
            placeholder="请输入项目描述"
            type="textarea"
            autosize
            required
            :disabled="!canEdit"
          />

          <van-field
            v-model="form.approveOpinion"
            name="approveOpinion"
            label="审批意见"
            type="textarea"
            autosize
            :disabled="true"
          />

          <van-field readonly label="项目状态">
            <template #button>
              <van-button
                size="small"
                type="primary"
                native-type="button"
                :disabled="!canEdit"
                @click="openProjectStatusNewModal(undefined)"
              >添加项目状态</van-button>
            </template>
          </van-field>

          <v-table
            is-horizontal-resize
            style="width:100%"
            :columns="projectStatusNewCol"
            :table-data="projectStatusNewArr"
            row-hover-color="#eee"
            row-click-color="#edf7ff"
            :row-click="projectStatusNewItemClick"
          ></v-table>

          <div class="projectStatusTip">温馨提示:每个月必须更新项目最新状态</div>

          <van-field readonly label="送样型号">
            <template #button>
              <van-button
                size="small"
                type="primary"
                native-type="button"
                :disabled="!canEdit"
                @click="openLockModal(undefined)"
              >添加送样型号</van-button>
            </template>
          </van-field>

          <v-table
            is-horizontal-resize
            style="width:100%"
            :columns="lockModalCol"
            :table-data="lockModelArr"
            row-hover-color="#eee"
            row-click-color="#edf7ff"
            :row-click="lockItemClick"
          ></v-table>

          <van-field readonly label="竞争品牌">
            <template #button>
              <van-button
                size="small"
                type="primary"
                native-type="button"
                :disabled="!canEdit"
                @click="openCompareModal(undefined)"
              >添加竞争品牌</van-button>
            </template>
          </van-field>

          <v-table
            is-horizontal-resize
            style="width:100%"
            :columns="compareModalCol"
            :table-data="competitiveBrandArr"
            row-hover-color="#eee"
            row-click-color="#edf7ff"
            :row-click="compareItemClick"
          ></v-table>
        </van-form>
        <div style="margin: .3rem;" v-if="recordCanEdit">
          <van-row type="flex">
            <van-col class="bottomBtnCol" v-if="pageType == 1">
              <van-button
                round
                block
                type="default"
                native-type="button"
                @click="canEditBtnClick"
              >{{ canEdit?'取消':'编辑' }}</van-button>
            </van-col>
            <van-col class="bottomBtnCol">
              <van-button
                round
                block
                type="info"
                native-type="button"
                :disabled="!canEdit"
                @click="okBtnClick"
              >确定</van-button>
            </van-col>
          </van-row>
        </div>
      </van-skeleton>
    </div>

    <van-popup v-model="projectStatusNewVisible" :close-on-click-overlay="false">
      <div class="lockModalContainer">
        <div class="lockModalTitle">{{ projectStatusNewTitle }}</div>
        <van-form ref="projectStatusNewForm" @submit="projectStatusNewFormSubmit">
          <van-field
            v-model="projectStatusNewDetail.projectStatusUpdate"
            label="项目最新状态"
            required
            placeholder="请输入项目最新状态"
            :disabled="projectStatusNewDetail.inputDisabled"
            :rules="[{ required:true, message:'请输入项目最新状态' }]"
          />
          <van-field
            v-model="projectStatusNewDetail.nextStep"
            label="下一步行动"
            required
            placeholder="请输入下一步行动"
            :disabled="projectStatusNewDetail.inputDisabled"
            :rules="[{ required:true, message:'请输入下一步行动' }]"
          />
          <van-field
            v-model="projectStatusNewDetail.companySupport"
            label="需要公司的支持"
            required
            placeholder="请输入需要公司的支持"
            :disabled="projectStatusNewDetail.inputDisabled"
            :rules="[{ required:true, message:'请输入需要公司的支持' }]"
          />
          <van-field
            readonly
            clickable
            :value="projectStatusNewDetail.projectMonth"
            label="月份"
            required
            placeholder="点击选择月份"
            :disabled="projectStatusNewDetail.inputDisabled"
            :rules="[{ required:true, message:'请选择月份' }]"
            @click="showYearMonthPicker = true"
          />
        </van-form>
        <van-row type="flex" justify="end" class="lockModalBtnContainer">
          <van-button size="small" class="lockModalBtn" @click="projectStatusNewVisible = false">关闭</van-button>
          <van-button
            size="small"
            type="danger"
            class="lockModalBtn"
            :disabled="projectStatusNewDetail.delDisabled"
            @click="deleteProjectStatusNewItem"
          >删除</van-button>
          <van-button
            size="small"
            type="info"
            class="lockModalBtn"
            :disabled="projectStatusNewDetail.inputDisabled"
            @click="projectStatusNewSaveBtnClick"
          >保存</van-button>
        </van-row>
      </div>
    </van-popup>

    <van-popup v-model="lockModalVisible" :close-on-click-overlay="false">
      <div class="lockModalContainer">
        <div class="lockModalTitle">{{ lockModalTitle }}</div>
        <van-form ref="lockForm" @submit="lockFormSubmit">
          <van-field
            v-model="lockPopop.model"
            label="型号"
            required
            :rules="[{required:true,message:'请输入型号'}]"
            placeholder="请输入型号"
          />
          <van-field
            v-model="lockPopop.quantity"
            label="预估数量（套）"
            required
            type="number"
            :rules="[{required:true,message:'请输入预估数量'}]"
            placeholder="请输入预估数量（套）"
          />
          <van-field v-model="lockPopop.price" label="价格" type="number" placeholder="请输入价格" />
          <van-field
            readonly
            clickable
            :value="lockPopop.estimateInstallYear"
            label="预计交楼年份"
            placeholder="点击选择预计交楼年份"
            required
            :rules="[{required:true,message:'请输入预计交楼年份'}]"
            @click="showYearPicker = true"
          />
          <van-field
            readonly
            clickable
            name="estimateInstallYear"
            :value="lockPopop.estimateInstallMonth"
            label="预计交楼月份"
            placeholder="点击选择预计交楼月份"
            required
            :rules="[{required:true,message:'请输入预计交楼月份'}]"
            @click="showMonthPicker = true"
          />
          <van-field v-model="lockPopop.remark" label="备注" type="textarea" placeholder="请输入备注" />
        </van-form>
        <van-row type="flex" justify="end" class="lockModalBtnContainer">
          <van-button size="small" class="lockModalBtn" @click="lockModalVisible = false">关闭</van-button>
          <van-button
            size="small"
            type="danger"
            class="lockModalBtn"
            :disabled="lockCurIndex == -1"
            @click="deleteLockItem"
          >删除</van-button>
          <van-button size="small" type="info" class="lockModalBtn" @click="lockSaveBtnClick">保存</van-button>
        </van-row>
      </div>
    </van-popup>
    <van-popup :lazy-render="false" v-model="showYearPicker" position="bottom">
      <van-picker
        ref="yearPicker"
        show-toolbar
        :columns="yearArr"
        :default-index="lockDefaultYearIndex"
        @confirm="yearConfirm"
        @cancel="showYearPicker = false"
      />
    </van-popup>
    <van-popup :lazy-render="false" v-model="showMonthPicker" position="bottom">
      <van-picker
        ref="monthPicker"
        show-toolbar
        :columns="monthArr"
        @confirm="monthConfirm"
        @cancel="showMonthPicker = false"
      />
    </van-popup>

    <van-popup v-model="compareModalVisible" :close-on-click-overlay="false">
      <div class="lockModalContainer">
        <div class="lockModalTitle">{{ compareModalTitle }}</div>
        <van-form ref="compareForm" @submit="compareFormSubmit">
          <van-field
            v-model="comparePopop.brand"
            label="竞争品牌"
            required
            :rules="[{required:true,message:'请输入竞争品牌'}]"
            placeholder="请输入竞争品牌"
          />
          <van-field
            v-model="comparePopop.competitor"
            label="竞争者（厂家/经销商）"
            required
            :rules="[{required:true,message:'请输入竞争者'}]"
            placeholder="请输入竞争者"
          />
          <van-field
            v-model="comparePopop.compProduct"
            label="型号"
            required
            :rules="[{required:true,message:'请输入型号'}]"
            placeholder="请输入型号"
          />
          <van-field v-model="comparePopop.price" label="报价" type="number" placeholder="请输入报价" />
          <!-- <van-field
          readonly
          clickable
          :value="comparePopop.brandTime"
          label="日期"
          placeholder="点击选择日期"
          @click="showBrandTimePicker = true"
          />-->
        </van-form>
        <van-row type="flex" justify="end" class="lockModalBtnContainer">
          <van-button size="small" class="lockModalBtn" @click="compareModalVisible = false">关闭</van-button>
          <van-button
            size="small"
            type="danger"
            class="lockModalBtn"
            :disabled="compareCurIndex == -1"
            @click="deleteCompareItem"
          >删除</van-button>
          <van-button size="small" type="info" class="lockModalBtn" @click="saveCompareBtnClick">保存</van-button>
        </van-row>
      </div>
    </van-popup>
    <van-calendar
      ref="brandTimeCalendar"
      v-model="showBrandTimePicker"
      :default-date="brandTimeDefaultDate"
      :min-date="minDate"
      :max-date="maxDate"
      @confirm="brandTimeConfirm"
    />
    <van-popup :lazy-render="false" v-model="showYearMonthPicker" position="bottom">
      <van-datetime-picker
        ref="yearMonthPicker"
        v-model="yearMonthCurDate"
        type="year-month"
        title="选择年月"
        :min-date="yearMonthMinDate"
        :max-date="yearMonthMaxDate"
        @confirm="yearMonthConfirm"
      />
    </van-popup>
  </div>
</template>

<script>
import Card from "@/components/Card";
import {
  _reportPeopleDict,
  _construcProgress,
  _projectTypeDict,
  _realEstatePropDict,
  _realEstateLevelDict,
  _proToGroundDict,
  _construcProgressDict,
} from "@/utils/dict";
import { mapActions, mapMutations } from "vuex";
import {
  Skeleton,
  Form,
  Field,
  Picker,
  Calendar,
  RadioGroup,
  Radio,
  Popup,
  Button,
  Search,
  NumberKeyboard,
  Toast,
  Row,
  Col,
  Icon,
  DatetimePicker,
} from "vant";
import Fuse from "fuse.js";
import { formatDate } from "@/utils";
import _ from "lodash";
export default {
  components: {
    Card,
    [Skeleton.name]: Skeleton,
    [Form.name]: Form,
    [Field.name]: Field,
    [Picker.name]: Picker,
    [Calendar.name]: Calendar,
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio,
    [Popup.name]: Popup,
    [Button.name]: Button,
    [Search.name]: Search,
    [NumberKeyboard.name]: NumberKeyboard,
    [Row.name]: Row,
    [Col.name]: Col,
    [Icon.name]: Icon,
    [DatetimePicker.name]: DatetimePicker,
  },
  data() {
    return {
      title: "",
      pageType: 0,
      loading: true,
      form: {
        serialNum: "",
        reportPeople: "",
        cusAddDocumentId: "",
        salesmanId: "",
        designInstitute: "",
        totalPackageCusId: "",
        projectName: "",
        projectSite: "",
        engineerAgentCusId: "",
        engineerAgentCusName: "",
        mainPerson: "",
        duty: "",
        mainPerPhone: "",
        mainPerson2: "",
        duty2: "",
        mainPerPhone2: "",
        mainPerson3: "",
        duty3: "",
        mainPerPhone3: "",
        doorFactoryCusId: "",
        referrer: "",
        referPhone: "",
        reportCompany: "",
        coverArea: "",
        construcProgress: "",
        projectType: "",
        projectRemark: "",
        approveOpinion: "",
        realEstateProp: "",
        realEstateLevel: "",
        proToGround: "",
      },
      // 表单项展示用数据
      showForm: {
        cusAddDocumentId_show: "",
        salesmanId_show: "",
        totalPackageCusId_show: "",
        engineerAgentCusId_show: "",
        doorFactoryCusId_show: "",
      },
      // 模糊搜索用弹窗控制
      popupCtr: {
        formName: "",
        showKey: "",
      },
      searchValue: "",
      popupVisible: false,
      searchArray: [],
      showSearchAdd: false,
      engineerAgentCusIdDisabled: false,

      reportPeopleArr: _reportPeopleDict,
      construcProgressArr: _construcProgressDict,
      projectTypeArr: _projectTypeDict,
      realEstatePropArr: _realEstatePropDict,
      realEstateLevelArr: _realEstateLevelDict,
      proToGroundArr: _proToGroundDict,

      salesmanIdArrOrigin: [],
      cusAddDocumentIdArrOrigin: [],
      totalPackageCusIdArrOrigin: [],
      engineerAgentCusIdArrOrigin: [],
      doorFactoryCusIdArrOrigin: [],

      projectStatusNewVisible: false,
      projectStatusNewTitle: "",
      projectStatusNewDetail: {
        projectStatusUpdate: "",
        nextStep: "",
        companySupport: "",
        projectMonth: "",
        delDisabled: true,
        inputDisabled: false,
      },
      projectStatusNewCurIndex: -1,

      // 送样型号相关参数
      lockModalVisible: false,
      lockModalTitle: "",

      lockPopop: {
        model: "",
        quantity: "",
        price: "",
        estimateInstallYear: "",
        estimateInstallMonth: "",
        remark: "",
      },
      lockCurIndex: -1,
      lockDefaultYearIndex: 0,

      showYearMonthPicker: false,
      showYearPicker: false,
      yearArr: _.range(2010, 2100),
      showMonthPicker: false,
      monthArr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
      yearMonthMinDate: new Date(),
      yearMonthMaxDate: new Date("2100/01/01"),
      yearMonthCurDate: new Date(),
      yearMonthDefDate: new Date(),

      // 竞品相关参数
      compareModalVisible: false,
      compareModalTitle: "",

      comparePopop: {
        brand: "",
        competitor: "",
        compProduct: "",
        price: "",
        brandTime: "",
      },

      compareCurIndex: -1,

      showBrandTimePicker: false,
      brandTimeDefaultDate: new Date(),
      // 样品型号和竞品列表数组
      lockModelArr: [],
      lockModelArrOrigin: [],
      competitiveBrandArr: [],
      competitiveBrandArrOrigin: [],
      projectStatusNewArr: [],
      projectStatusNewArrOrigin: [],

      projectStatusNewCol: [
        {
          field: "projectStatusUpdate",
          title: "项目最新状态",
          titleAlign: "center",
          columnAlign: "center",
          isResize: true,
          width: 30,
        },
        {
          field: "nextStep",
          title: "下一步行动",
          titleAlign: "center",
          columnAlign: "center",
          isResize: true,
          width: 30,
        },
        {
          field: "companySupport",
          title: "需要公司的支持",
          titleAlign: "center",
          columnAlign: "center",
          isResize: true,
          width: 30,
        },
        {
          field: "projectMonth",
          title: "月份",
          titleAlign: "center",
          columnAlign: "center",
          isResize: true,
          width: 30,
        },
      ],
      lockModalCol: [
        {
          field: "model",
          title: "型号",
          titleAlign: "center",
          columnAlign: "center",
          isResize: true,
          width: 30,
        },
        {
          field: "quantity",
          title: "预估数量（套）",
          titleAlign: "center",
          columnAlign: "center",
          isResize: true,
          width: 30,
        },
        {
          field: "price",
          title: "价格",
          titleAlign: "center",
          columnAlign: "center",
          isResize: true,
          width: 30,
        },
        {
          field: "estimateInstallYear",
          title: "预计交楼年份",
          titleAlign: "center",
          columnAlign: "center",
          isResize: true,
          width: 30,
        },
        {
          field: "estimateInstallMonth",
          title: "预计交楼月份",
          titleAlign: "center",
          columnAlign: "center",
          isResize: true,
          width: 30,
        },
      ],
      compareModalCol: [
        {
          field: "brand",
          title: "竞争品牌",
          titleAlign: "center",
          columnAlign: "center",
          isResize: true,
          width: 30,
        },
        {
          field: "competitor",
          title: "竞争者(厂家/经销商)",
          titleAlign: "center",
          columnAlign: "center",
          isResize: true,
          width: 30,
        },
        {
          field: "compProduct",
          title: "竞争产品",
          titleAlign: "center",
          columnAlign: "center",
          isResize: true,
          width: 30,
        },
        {
          field: "price",
          title: "报价",
          titleAlign: "center",
          columnAlign: "center",
          isResize: true,
          width: 30,
        },
        // {
        //   field: "brandTime",
        //   title: "日期",
        //   titleAlign: "center",
        //   columnAlign: "center",
        //   isResize: true,
        //   width: 30,
        // },
      ],
      minDate: new Date("2000/01/01"),
      maxDate: new Date("2100/01/01"),
      canEdit: false,
      recordCanEdit: true, // 作废或者审批拒绝则不能编辑
    };
  },
  created() {
    if (this.$route.query.type == "add") {
      this.title = "添加项目报备";
      document.title = "添加项目报备";
      this.pageType = 0;
      this.canEdit = true;
    } else {
      this.title = "编辑项目报备";
      document.title = "编辑项目报备";
      this.pageType = 1;
    }
  },
  mounted() {
    this.loading = true;
    this.initData();
    this.resetLockPopop();
    this.resetComparePopop();
    this.resetProjectStatusNewDetail();
  },
  beforeDestroy() {
    this.resetDocsDetail();
  },
  methods: {
    ...mapActions({
      getCusDocsList: "projectReport/getCusDocsList",
      getTotalPackageList: "projectReport/getTotalPackageList",
      getEngineerAgentList: "projectReport/getEngineerAgentList",
      getDoorFactoryList: "projectReport/getDoorFactoryList",
      querySalesman: "cusAddDocs/querySalesman",
      addProjectReport: "projectReport/addProjectReport",
      updateProjectReport: "projectReport/updateProjectReport",
      getCompetitivebrand: "projectReport/getCompetitivebrand",
      getLockModel: "projectReport/getLockModel",
      getProjectStatusList: "projectReport/getProjectStatusList",
    }),
    ...mapMutations({
      resetDocsDetail: "projectReport/resetDocsDetail",
    }),
    initData() {
      let detail = this.$store.state.projectReport.projectReportDetail;
      if (this.pageType == 1 && (detail.delFlag || detail.approveStatus == 0)) {
        this.recordCanEdit = false;
      }
      for (const key in detail) {
        if (detail.hasOwnProperty(key)) {
          const element = detail[key];
          this.form[key] = "" + element;
        }
      }
      if (detail.proToGround == 1) {
        this.engineerAgentCusIdDisabled = true;
      }
      Promise.all([this.getCusDocsList(), this.querySalesman()])
        .then((res) => {
          console.log(res);
          // this.salesmanArr = res[1].data;
          let salesmanArr = res[1].data;
          let cusArr = res[0].data;
          if (salesmanArr.length) {
            this.salesmanIdArrOrigin = JSON.parse(JSON.stringify(salesmanArr));
            if (this.pageType == 1) {
              for (let i = 0, len = salesmanArr.length; i < len; i++) {
                if (salesmanArr[i].id == detail.salesmanId) {
                  this.showForm.salesmanId_show = salesmanArr[i].nickName;
                  break;
                }
              }
            }
          }

          // this.cusAddDocumentIdArr = res[0].data;
          if (cusArr.length) {
            this.cusAddDocumentIdArrOrigin = JSON.parse(JSON.stringify(cusArr));
            if (this.pageType == 1) {
              for (let i = 0, len = cusArr.length; i < len; i++) {
                if (cusArr[i].id == detail.cusAddDocumentId) {
                  this.showForm.cusAddDocumentId_show = cusArr[i].cusFullName;
                  break;
                }
              }
            }
          }
          this.loading = false;
        })
        .catch((err) => {
          console.log(err);
          this.loading = false;
        });

      this.getTotalPackageList()
        .then((res) => {
          let arr = res.data;
          if (arr.length) {
            this.totalPackageCusIdArrOrigin = JSON.parse(JSON.stringify(arr));
            if (this.pageType == 1) {
              for (let i = 0, len = arr.length; i < len; i++) {
                if (arr[i].id == detail.cusAddDocumentId) {
                  this.showForm.totalPackageCusId_show = arr[i].cusFullName;
                  break;
                }
              }
            }
          }
        })
        .catch((err) => {
          console.log(err);
        });

      this.getEngineerAgentList()
        .then((res) => {
          let arr = res.data;
          if (arr.length) {
            this.engineerAgentCusIdArrOrigin = JSON.parse(JSON.stringify(arr));
            if (this.pageType == 1) {
              for (let i = 0, len = arr.length; i < len; i++) {
                if (arr[i].id == detail.engineerAgentCusId) {
                  this.showForm.engineerAgentCusId_show = arr[i].cusFullName;
                  this.form.engineerAgentCusName = arr[i].cusFullName;
                  break;
                }
              }
            }
          }
        })
        .catch((err) => {
          console.log(err);
        });

      this.getDoorFactoryList()
        .then((res) => {
          let arr = res.data;
          if (arr.length) {
            this.doorFactoryCusIdArrOrigin = JSON.parse(JSON.stringify(arr));
            if (this.pageType == 1) {
              for (let i = 0, len = arr.length; i < len; i++) {
                if (arr[i].id == detail.doorFactoryCusId) {
                  this.showForm.doorFactoryCusId_show = arr[i].cusFullName;
                  break;
                }
              }
            }
          }
        })
        .catch((err) => {
          console.log(err);
        });

      if (this.pageType == 1 && this.form.id) {
        this.getLockModel({
          sortOrder: "asc",
          projectReportId: this.form.id,
        })
          .then((res) => {
            console.log("lock", res);
            let arr = res.res;
            this.lockModelArr = arr;
            this.lockModelArrOrigin = JSON.parse(JSON.stringify(arr));
          })
          .catch((err) => {
            console.log(err);
          });
        this.getCompetitivebrand({
          sortOrder: "asc",
          projectReportId: this.form.id,
        })
          .then((res) => {
            console.log("compare", res);
            let arr = res.res;
            arr.forEach((e, i) => {
              if (e.brandTime) {
                arr[i].brandTime = formatDate(
                  new Date(e.brandTime),
                  "yyyy-MM-dd"
                );
              }
            });
            this.competitiveBrandArr = arr;
            this.competitiveBrandArrOrigin = JSON.parse(JSON.stringify(arr));
          })
          .catch((err) => {
            console.log(err);
          });
        this.getProjectStatusList({
          sortOrder: "asc",
          id: this.form.id,
        })
          .then((res) => {
            console.log("projectStatus", res);
            let arr = res.data;
            this.projectStatusNewArr = arr;
            this.projectStatusNewArrOrigin = JSON.parse(JSON.stringify(arr));
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
    salesmanValidate(val) {
      return this.form.salesmanId ? true : false;
    },
    cusAddDocsValidate(val) {
      return this.form.cusAddDocumentId ? true : false;
    },
    engineerAgentCusIdValidate(val) {
      console.log("engineerAgentCusIdValidate", this.form.engineerAgentCusId);
      if (
        this.form.proToGround == "1" ||
        this.form.proToGround == "" ||
        this.form.engineerAgentCusName != ""
      ) {
        return true;
      } else if (this.form.engineerAgentCusId == "0") {
        return false;
      } else {
        return this.form.engineerAgentCusId ? true : false;
      }
    },
    proToGroundChange(val) {
      console.log("proToGroundChange", val);
      if (val == 1) {
        this.form.engineerAgentCusId = "0";
        this.form.engineerAgentCusName = "";
        this.showForm.engineerAgentCusId_show = "";
        this.engineerAgentCusIdDisabled = true;
        this.$refs.form.resetValidation("engineerAgentCusId");
      } else {
        this.engineerAgentCusIdDisabled = false;
      }
    },
    openFuzzyPopup(formName, showKey, showSearchAdd) {//打开模糊搜索
      if (this.canEdit) {
        this.popupCtr.formName = formName;
        this.popupCtr.showKey = showKey;
        this.searchValue = "";
        this.searchArray = [];
        this.showSearchAdd = showSearchAdd;
        this.popupVisible = true;
      }
    },
    fuzzyPopupOpened() {
      let child = this.$refs.popupDom.getElementsByTagName("input");
      child[0].focus();
    },
    fuzzyItemClick(item) {//模糊搜索选项点击
      console.log(item, this.popupCtr);
      this.form[this.popupCtr.formName] = item.id;
      this.showForm[`${this.popupCtr.formName}_show`] =
        item[this.popupCtr.showKey];
      if (this.popupCtr.formName == "engineerAgentCusId") {
        this.form.engineerAgentCusName = item[this.popupCtr.showKey];
      }
      this.popupCtr.formName = "";
      this.popupCtr.showKey = "";
      this.searchValue = "";
      this.searchArray = [];
      this.popupVisible = false;
    },
    fuzzyInput(value) {//模糊搜索输入
      console.log("value", value);
      if (value == "") {
        this.searchArray = [];
      } else {
        const options = {
          includeScore: true,
          // Search in `author` and in `tags` array
          keys: [this.popupCtr.showKey],
        };
        const fuse = new Fuse(
          this[`${this.popupCtr.formName}ArrOrigin`],
          options
        );
        const result = fuse.search(value);
        this.searchArray = [];
        result.forEach((e) => {
          this.searchArray.push(e.item);
        });
      }
    },
    fuzzyAdd() {//模糊搜索点添加
      if (this.searchValue) {
        this.form[this.popupCtr.formName] = this.searchValue;
        this.showForm[`${this.popupCtr.formName}_show`] = this.searchValue;
        if (this.popupCtr.formName == "engineerAgentCusId") {
          this.form.engineerAgentCusName = this.searchValue;
          this.form.engineerAgentCusId = "0";
        }
        this.popupVisible = false;
      }
    },
    fuzzyClear() {
      console.log("clear");
      this.form[this.popupCtr.formName] = "";
      this.showForm[`${this.popupCtr.formName}_show`] = "";
    },
    openProjectStatusNewModal(item) {
      if (this.canEdit) {
        if (item) {
          console.log("item", item);
          let delDisabled = false;
          let inputDisabled = false;
          if (item.projectMonth < formatDate(new Date(), "yyyy-MM")) {
            delDisabled = true;
            inputDisabled = true;
          }
          this.projectStatusNewDetail = { ...item, delDisabled, inputDisabled };
          this.projectStatusNewTitle = "编辑项目状态";
        } else {
          this.resetProjectStatusNewDetail();
          this.projectStatusNewTitle = "添加项目状态";
        }
        this.projectStatusNewVisible = true;
        this.$nextTick(() => {
          if (item) {
          }
        });
      }
    },
    openLockModal(item) {
      // 打开送样型号弹窗
      if (this.canEdit) {
        if (item) {
          this.lockPopop = item;
          this.lockModalTitle = "编辑送样型号";
        } else {
          this.resetLockPopop();
          this.lockModalTitle = "添加送样型号";
        }
        this.lockModalVisible = true;
        this.$nextTick(() => {
          if (item) {
            if (item.estimateInstallYear) {
              this.$refs.yearPicker.setValues([item.estimateInstallYear]);
            }
            if (item.estimateInstallMonth) {
              this.$refs.monthPicker.setValues([item.estimateInstallMonth]);
            }
          }
        });
      }
    },
    yearConfirm(value) {
      // 年份确认
      console.log(value);
      this.lockPopop.estimateInstallYear = value;
      this.showYearPicker = false;
    },
    monthConfirm(value) {
      // 月份确认
      this.lockPopop.estimateInstallMonth = value;
      this.showMonthPicker = false;
    },
    yearMonthConfirm(value) {
      console.log(value);
      this.projectStatusNewDetail.projectMonth = formatDate(value, "yyyy-MM");
      this.showYearMonthPicker = false;
    },
    projectStatusNewSaveBtnClick() {
      this.$refs.projectStatusNewForm.submit();
    },
    projectStatusNewFormSubmit() {
      this.saveProjectStatusNew();
    },
    lockSaveBtnClick() {
      this.$refs.lockForm.submit();
    },
    lockFormSubmit() {
      this.saveLockModel();
    },
    saveCompareBtnClick() {
      this.$refs.compareForm.submit();
    },
    compareFormSubmit() {
      this.saveCompare();
    },
    saveProjectStatusNew() {
      if (this.projectStatusNewDetail.projectMonth) {
        this.projectStatusNewDetail.projectMonth = formatDate(
          new Date(this.projectStatusNewDetail.projectMonth),
          "yyyy-MM"
        );
      }
      let obj = JSON.parse(JSON.stringify(this.projectStatusNewDetail));

      if (this.projectStatusNewCurIndex == -1) {
        this.projectStatusNewArr.push(obj);
        this.projectStatusNewVisible = false;
      } else {
        this.$set(this.projectStatusNewArr, this.projectStatusNewCurIndex, obj);
      }
      this.projectStatusNewVisible = false;
    },
    saveLockModel() {
      // 送样型号保存点击
      let obj = JSON.parse(JSON.stringify(this.lockPopop));
      if (this.lockCurIndex == -1) {
        this.lockModelArr.push(obj);
      } else {
        this.$set(this.lockModelArr, this.lockCurIndex, obj);
      }

      this.lockModalVisible = false;
    },
    saveCompare() {
      // 竞品保存点击
      if (!this.comparePopop.brandTime) {
        this.comparePopop.brandTime = formatDate(new Date(), "yyyy-MM-dd");
      }
      let obj = JSON.parse(JSON.stringify(this.comparePopop));

      if (this.compareCurIndex == -1) {
        this.competitiveBrandArr.push(obj);
        this.compareModalVisible = false;
      } else {
        this.$set(this.competitiveBrandArr, this.compareCurIndex, obj);
      }
      this.compareModalVisible = false;
    },
    brandTimeConfirm(date) {
      // 竞品日期确定点击
      this.comparePopop.brandTime = formatDate(date, "yyyy-MM-dd");
      this.showBrandTimePicker = false;
    },
    resetProjectStatusNewDetail() {
      this.projectStatusNewCurIndex = -1;
      this.projectStatusNewDetail = {
        projectStatusUpdate: "",
        nextStep: "",
        companySupport: "",
        projectMonth: "",
        delDisabled: true,
        inputDisabled: false,
      };
    },
    resetLockPopop() {
      // 重置送样型号相关信息
      let year = new Date().getFullYear();
      this.lockDefaultYearIndex = year - 2010;
      this.$refs.yearPicker.setValues([year]);
      this.$refs.monthPicker.setValues([1]);
      this.lockPopop = {
        model: "",
        quantity: "",
        price: "",
        estimateInstallYear: "",
        estimateInstallMonth: "",
        remark: "",
      };
      this.lockCurIndex = -1;
    },
    deleteProjectStatusNewItem() {
      if (this.projectStatusNewCurIndex > -1) {
        this.$delete(this.projectStatusNewArr, this.projectStatusNewCurIndex);
        this.projectStatusNewVisible = false;
      }
    },
    deleteLockItem() {
      //删除送样型号
      if (this.lockCurIndex > -1) {
        this.$delete(this.lockModelArr, this.lockCurIndex);
        this.lockModalVisible = false;
      }
    },
    projectStatusNewItemClick(rowIndex, rowData, column) {
      this.projectStatusNewCurIndex = rowIndex;
      this.openProjectStatusNewModal(JSON.parse(JSON.stringify(rowData)));
    },
    lockItemClick(rowIndex, rowData, column) {
      // 送样型号表格项点击
      console.log(rowIndex, rowData, column);
      this.lockCurIndex = rowIndex;
      this.openLockModal(JSON.parse(JSON.stringify(rowData)));
    },
    openCompareModal(item) {
      // 打开竞品弹窗
      if (this.canEdit) {
        if (item) {
          this.comparePopop = item;
          this.compareModalTitle = "编辑竞争品牌";
          this.brandTimeDefaultDate = new Date(item.brandTime);
        } else {
          this.resetComparePopop();
          this.compareModalTitle = "添加竞争品牌";
        }
        this.compareModalVisible = true;
        this.$nextTick(() => {
          if (item) {
            this.$refs.brandTimeCalendar.reset();
          }
        });
      }
    },
    compareItemClick(rowIndex, rowData, column) {
      // 竞品项点击
      console.log(rowIndex, rowData, column);
      this.compareCurIndex = rowIndex;
      this.openCompareModal(JSON.parse(JSON.stringify(rowData)));
    },
    resetComparePopop() {
      // 重置竞品相关信息
      this.brandTimeDefaultDate = new Date();
      this.comparePopop = {
        brand: "",
        competitor: "",
        compProduct: "",
        price: "",
        brandTime: "",
      };
      this.compareCurIndex = -1;
      this.$refs.brandTimeCalendar.reset();
    },
    deleteCompareItem() {
      // 删除竞品
      if (this.compareCurIndex > -1) {
        this.$delete(this.competitiveBrandArr, this.compareCurIndex);
        this.compareModalVisible = false;
      }
    },
    canEditBtnClick() {
      if (this.canEdit) {
        // 取消 还原数据
        this.form = {
          serialNum: "",
          reportPeople: "",
          cusAddDocumentId: "",
          salesmanId: "",
          designInstitute: "",
          totalPackageCusId: "",
          projectName: "",
          projectSite: "",
          engineerAgentCusId: "",
          mainPerson: "",
          mainPerPhone: "",
          doorFactoryCusId: "",
          referrer: "",
          referPhone: "",
          reportCompany: "",
          coverArea: "",
          construcProgress: "",
          projectType: "",
          projectRemark: "",
          approveOpinion: "",
          realEstateProp: "",
          realEstateLevel: "",
          proToGround: "",
        };

        let detail = this.$store.state.projectReport.projectReportDetail;
        for (const key in detail) {
          if (detail.hasOwnProperty(key)) {
            const element = detail[key];
            this.form[key] = "" + element;
          }
        }

        let salesmanArr = this.salesmanIdArrOrigin;
        for (let i = 0, len = salesmanArr.length; i < len; i++) {
          if (salesmanArr[i].id == detail.salesmanId) {
            this.showForm.salesmanId_show = salesmanArr[i].nickName;
            break;
          }
        }
        let cusArr = this.cusAddDocumentIdArrOrigin;
        for (let i = 0, len = cusArr.length; i < len; i++) {
          if (cusArr[i].id == detail.cusAddDocumentId) {
            this.showForm.cusAddDocumentId_show = cusArr[i].cusFullName;
            break;
          }
        }

        for (
          let i = 0, len = this.totalPackageCusIdArrOrigin.length;
          i < len;
          i++
        ) {
          if (
            this.totalPackageCusIdArrOrigin[i].id == detail.cusAddDocumentId
          ) {
            this.showForm.totalPackageCusId_show = this.totalPackageCusIdArrOrigin[
              i
            ].cusFullName;
            break;
          }
        }

        for (
          let i = 0, len = this.engineerAgentCusIdArrOrigin.length;
          i < len;
          i++
        ) {
          if (
            this.engineerAgentCusIdArrOrigin[i].id == detail.engineerAgentCusId
          ) {
            this.showForm.engineerAgentCusId_show = this.engineerAgentCusIdArrOrigin[
              i
            ].cusFullName;
            break;
          }
        }
        for (
          let i = 0, len = this.doorFactoryCusIdArrOrigin.length;
          i < len;
          i++
        ) {
          if (this.doorFactoryCusIdArrOrigin[i].id == detail.doorFactoryCusId) {
            this.showForm.doorFactoryCusId_show = this.doorFactoryCusIdArrOrigin[
              i
            ].cusFullName;
            break;
          }
        }

        this.lockModelArr = JSON.parse(JSON.stringify(this.lockModelArrOrigin));
        this.competitiveBrandArr = JSON.parse(
          JSON.stringify(this.competitiveBrandArrOrigin)
        );
        this.projectStatusNewArr = JSON.parse(
          JSON.stringify(this.projectStatusNewArrOrigin)
        );
      }
      this.canEdit = !this.canEdit;
    },
    okBtnClick() {
      this.$refs.form.submit();
    },
    back() {
      this.$router.go(-1);
    },
    formSubmited() {
      if (this.projectStatusNewArr.length == 0) {
        return Toast("项目状态不能为空");
      }
      if (this.lockModelArr.length == 0) {
        return Toast("送样型号不能为空");
      }
      if (this.competitiveBrandArr.length == 0) {
        return Toast("竞争品牌不能为空");
      }
      if (this.pageType == 0) {
        let lockModelStr = JSON.stringify(this.lockModelArr);
        let competitiveBrandStr = JSON.stringify(this.competitiveBrandArr);
        let projectStatusStr = JSON.stringify(this.projectStatusNewArr);
        this.form.lockModel = lockModelStr;
        this.form.competitiveBrand = competitiveBrandStr;
        this.form.projectStatusNew = projectStatusStr;
        this.addProjectReport(this.form)
          .then((res) => {
            console.log(res);
            if (res.success) {
              Toast.success("新建成功");
              this.$router.go(-1);
            } else {
              Toast.fail(`新建失败：${res.message}`);
            }
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        let arr = JSON.parse(JSON.stringify(this.competitiveBrandArr));
        arr.forEach((e, i) => {
          if (e.brandTime) {
            arr[i].brandTime = new Date(e.brandTime).valueOf(); // 更新的接口这个字段是时间戳
          }
        });
        let lockModelStr = JSON.stringify(this.lockModelArr);
        let competitiveBrandStr = JSON.stringify(arr);
        let projectStatusStr = JSON.stringify(this.projectStatusNewArr);
        this.form.lockModel = lockModelStr;
        this.form.competitiveBrand = competitiveBrandStr;
        this.form.projectStatusNew = projectStatusStr;

        this.updateProjectReport(this.form)
          .then((res) => {
            console.log(res);
            if (res.success) {
              Toast.success("更新成功");
              // this.$router.go(-1);
            } else {
              Toast.fail(`更新失败：${res.message}`);
            }
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
  },
};
</script>

<style lang="scss">
.project-report-detail {
  .headTitle {
    font-size: 24px;
    padding-bottom: 12px;
    align-items: center;
    display: flex;
  }
  .van-radio {
    margin-bottom: 8px;
  }
  .salesmanPopupContainer {
    max-height: 100vh;
    overflow: hidden;
    .salesmanItemContainer {
      overflow: auto;
      position: relative;
      max-height: 600px;
      .salesmanItem {
        padding: 8px 12px;
      }
    }
  }
  .lockModalContainer {
    width: 320px;
    .lockModalTitle {
      padding: 8px 8px 8px 12px;
      font-size: 20px;
    }
    .lockModalBtnContainer {
      margin: 8px;
      .lockModalBtn {
        margin-left: 8px;
      }
    }
  }
  .bottomBtnCol {
    flex: 1;
    padding: 8px;
  }
  .projectStatusTip {
    padding: 12px;
    color: red;
  }
}
</style>